package com.fpx.order.plat.bussiness.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ebay.sdk.ApiException;
import com.ebay.sdk.SdkException;
import com.ebay.sdk.SdkSoapException;
import com.fpx.api.service.IAmazonService;
import com.fpx.api.service.IEbayService;
import com.fpx.api.service.ISmtService;
import com.fpx.order.plat.bussiness.cache.CacheManage;
import com.fpx.order.plat.bussiness.entity.CustomerShop;
import com.fpx.order.plat.bussiness.service.customer.ICustomerShopService;
import com.fpx.order.plat.bussiness.system.CacheConstants;
import com.fpx.order.plat.bussiness.system.PlatConstants;
import com.fpx.order.plat.common.utils.DateFormatUtils;
import com.fpx.order.plat.web.utils.AjaxUtils;

/**
 * desc: 海外平台授权
 * 
 * @author xiangtao(xiangtao@4px.com)
 * @date 2015年11月25日 下午3:27:18
 * @version 1.0
 */
@Controller
public class OverseaPlatAuthorizeController {

	@SuppressWarnings("unused")
	private static final SimpleDateFormat FORMATE = new SimpleDateFormat(
			"yyyyMMddHHmmss");

	private final static Logger LOGGER = Logger
			.getLogger(OverseaPlatAuthorizeController.class);

	/**
	 * 电商平台类型 ---ebay 零售
	 */
	private final static String EBAY = "E";

	/**
	 * 电商平台类型 ---amazon 零售
	 */
	private final static String AMAZON = "A";
	/**
	 * 电商平台类型 ---aliexpress 零售
	 */
	private final static String SMT = "S";
	/**
	 * 电商平台类型 ---Wish 零售
	 */
	private final static String WISH = "W";

	@Autowired
	private ICustomerShopService customerShopService;

	@Autowired
	private IEbayService ebayService;

	@Autowired
	private IAmazonService amazonService;

	@Autowired
	private ISmtService smtService;

	@Autowired
	private CacheManage cacheManage;

	private Map<String, String> configMap;

	/**
	 * ebay、亚马逊、速卖通授权接口
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/authorize")
	public ModelAndView authorize(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		Map<String, String> map = new HashMap<String, String>();
		String url = "merchant/authorize";
		try {
			// 店铺编号
			String csid = ServletRequestUtils.getStringParameter(request,
					"cs_id");
			if (StringUtils.isEmpty(csid)) {
				map.put("errorMessage", "参数不能为空");
				return new ModelAndView("merchant/error", map);
			}
			CustomerShop customer = null;
			try {
				customer = customerShopService.findByCsidCustomer(csid);
			} catch (Exception e) {
				map.put("errorMessage", "参数不正确");
				return new ModelAndView("merchant/error", map);
			}
			if (null != customer) {
				String cs_id = customer.getCs_id();// 店铺编号
				String order_source = customer.getCs_platform_code();
				String cs_name = customer.getCs_name();// 商铺名称
				// ebay零售
				if (EBAY.equals(order_source)) {
					try {
						configMap = cacheManage
								.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_EBAY);
						map = ebayService.getEbayUrl(configMap);
						System.out.println("----------------------ebay授权URL："
								+ map.get("ebayUrl"));
						map.put("ebayNickName", cs_name);
						map.put("ebayCustomerNo", cs_id);
						map.put("ebayOrderSource", order_source);
						map.put("pageIndex", "1");
					} catch (Exception e) {
						url = "merchant/error";
						map.put("errorMessage", "获取Ebay卖家授权登录URL异常");
					}
				}
				// amazon 零售
				else if (AMAZON.equals(order_source)) {
					// 从缓取
					configMap = cacheManage
							.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_AMAZON);
					String site = customer.getCs_site();
					if (StringUtils.isNotEmpty(site)) {
						try {
							String amUrl = amazonService
									.getAmazonSignInUrl(site);
							map.put("amNickName", cs_name);
							map.put("amCustomerNo", cs_id);
							map.put("amOrderSource", order_source);
							map.put("amUrl", amUrl);
							map.put("amAppNum",
									configMap.get("applicationNum." + site));
							map.put("amAppName",
									configMap.get("applicationName." + site));
							map.put("pageIndex", "2");
						} catch (Exception e) {
							url = "merchant/error";
							map.put("errorMessage", "获取亚马逊卖家授权登录URL异常");
						}
					} else {
						url = "merchant/error";
						map.put("errorMessage", "亚马逊店铺【" + cs_name + "】站点未维护");
					}
				}
				// SMT 零售
				else if (SMT.equals(order_source)) {
					// 从缓取
					configMap = cacheManage
							.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_SMT);
					String aliexpressUrl = smtService.getSMTSignInUrl(cs_id,
							configMap);
					map.put("smtNickName", cs_name);
					map.put("smtUrl", aliexpressUrl);
					map.put("pageIndex", "3");
				} else if (WISH.equals(order_source)) {
					map.put("smtNickName", cs_name);
					map.put("wiCustomerNo", cs_id);
					map.put("pageIndex", "4");
				} else {
					url = "merchant/error";
					map.put("errorMessage", "电商平台类型参数与WMC电商供应链平台不对匹配！");
				}
			} else {
				url = "merchant/error";
				map.put("errorMessage", "店铺编号【" + csid
						+ "】在WMC电商供应链平台未维护或维护有误！");
			}
		} catch (Exception e) {
			LOGGER.error("平台授权时发生异常 ---异常信息:" + e.getMessage());
		}
		return new ModelAndView(url, map);
	}

	/**
	 * 保存ebay、亚马逊授权Token
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/saveAuthorize", method = RequestMethod.POST)
	public void saveAuthorize(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("result", "failure");
		try {
			String cs_platform_code = ServletRequestUtils.getStringParameter(
					request, "order_source");
			// 店铺编号
			String cs_id = ServletRequestUtils.getStringParameter(request,
					"customerNo");
			String cs_name = ServletRequestUtils.getStringParameter(request,
					"nickName");
			if (StringUtils.isEmpty(cs_platform_code)) {
				AjaxUtils.renderJson(response, JSONObject.fromObject(dataMap)
						.toString());
				return;
			}
			CustomerShop customer = new CustomerShop();
			customer.setCs_status(PlatConstants.CS_STUTAS_ON);
			customer.setCs_name(cs_name);
			// ebay零售
			if (EBAY.equals(cs_platform_code)) {
				String ebaySessionId = ServletRequestUtils.getStringParameter(
						request, "ebaySessionId");

				configMap = cacheManage
						.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_EBAY);
				Map<String, String> respMap =getEabyToken(
						ebaySessionId, configMap);
				if ("failure".equals(respMap.get("flag"))) {
					dataMap.put("result", " Ebay授权获取Token异常");
					LOGGER.error("ebay授权获取Token异常:"+respMap.get("msg"));
					AjaxUtils.renderJson(response,
							JSONObject.fromObject(dataMap).toString());
					return;
				}
				customer.setCs_token(respMap.get("token"));
				customer.setCs_token_timeout(respMap.get("expirationTime"));
			}
			// amazon 零售
			else if (AMAZON.equals(cs_platform_code)) {
				// 授权返回的Token
				String merchantId = ServletRequestUtils.getStringParameter(
						request, "merchantId");
				String marketplaceId = ServletRequestUtils.getStringParameter(
						request, "marketplaceId");
				if (StringUtils.isEmpty(merchantId)
						|| StringUtils.isEmpty(marketplaceId)) {
					dataMap.put("result", "亚马逊授权MerchantId或MarketplaceId为空");
					AjaxUtils.renderJson(response,
							JSONObject.fromObject(dataMap).toString());
					return;
				}
				customer.setCs_token(merchantId);
			}
			customer.setCs_authorize(PlatConstants.IS_AUTH_Y);
			customer.setCs_id(cs_id);
			customerShopService.updateAuthInfo(customer);
			dataMap.put("result", "success");
		} catch (Exception e) {
			LOGGER.error("保存授权信息时发生异常---异常信息：" + e.getMessage());
			dataMap.put("result", "保存授权信息时发生异常");
			AjaxUtils.renderJson(response, JSONObject.fromObject(dataMap)
					.toString());
			return;
		}
		AjaxUtils.renderJson(response, JSONObject.fromObject(dataMap)
				.toString());
	}
	
	public Map<String,String> getEabyToken(String ebaySessionId, Map<String,String>configMap){
		 Map<String,String> respMap=null;
		 try {
			respMap=ebayService.getEbayToken(ebaySessionId, configMap);
			if(respMap!=null&&StringUtils.isNotEmpty(respMap.get("token"))){
				respMap.put("flag", "success");
			}
		} catch (ApiException e) {
			respMap=new HashMap<String,String>();
			respMap.put("flag", "failure");
			respMap.put("msg", e.getMessage());
		} catch (SdkSoapException e) {
			respMap=new HashMap<String,String>();
			respMap.put("flag", "failure");
			respMap.put("msg", e.getMessage());
		} catch (SdkException e) {
			respMap=new HashMap<String,String>();
			respMap.put("flag", "failure");
			respMap.put("msg", e.getMessage());
		}catch(Exception e){
			respMap=new HashMap<String,String>();
			respMap.put("flag", "failure");
			respMap.put("msg", e.getMessage());
		} 
		 return respMap;
	}
	
	
	
	/**
	 * 提供给速卖通回调的url 地址需要在sdk 的配置文件配置
	 * 
	 * @param request
	 * @return
	 * @throws ECLinkServiceException
	 */
	@ResponseBody
	@RequestMapping(value = "/aliexpressRedirect")
	public ModelAndView aliexpressRedirect(HttpServletRequest request)
			throws IOException {
		LOGGER.error("---------------------开始执行速卖通授权回调--------------------------");
		Map<String, String> map = new HashMap<String, String>();
		// 原传递给速卖通的自定义参数
		String cs_id = request.getParameter("state");
		// 短授权码
		String code = request.getParameter("code");
		// 获取长授权码
		configMap = cacheManage
				.getPaltSysConfig(CacheConstants.SYSCONFIG_KEY_SMT);
		@SuppressWarnings("rawtypes")
		Map tokenMap = smtService.getSmtLongToken(code, configMap);
		if (tokenMap == null || tokenMap.isEmpty()) {
			map.put("errorMessage", "店铺编号【" + cs_id + "】授权失败，返回的长令牌为空！");
			LOGGER.error(map.get("errorMessage"));
			return new ModelAndView("merchant/error", map);
		}
		JSONObject jsonObject=JSONObject.fromObject(tokenMap);
		
		LOGGER.info(">>>>>>【SMT】获取到速卖通授权消息串:"+jsonObject.toString());
		
		// 授权令牌
		String longToken = (String) tokenMap.get("refresh_token");
		
		// 有效期
		String refresh_token_timeout = (String) tokenMap
				.get("refresh_token_timeout");
		try{
			Date d= DateFormatUtils.stringToDate(refresh_token_timeout, "yyyyMMddHHmmssSSSZ");
			refresh_token_timeout= DateFormatUtils.dateToString(d, "yyyy-MM-dd HH:mm:ss");
		}catch(Exception e){
			try {
				refresh_token_timeout=DateFormatUtils.getSysDateTime("yyyy-MM-dd");
			} catch (ParseException e1) {
				refresh_token_timeout="1970-1-1";
				LOGGER.error(">>>获取当前时间错误");
			}
		}
		LOGGER.info(">>>【SMT】速卖通授权token:"+longToken+" 过期token时间:"+refresh_token_timeout);
		
		// 保存速卖通授权
		// state 自定义参数
		if (!StringUtils.isEmpty(cs_id) && !StringUtils.isEmpty(longToken)) {
			try {
				CustomerShop customer = new CustomerShop();
				customer.setCs_status(PlatConstants.CS_STUTAS_ON);
				customer.setCs_token(longToken);
				customer.setCs_token_timeout(refresh_token_timeout);
				customer.setCs_authorize(PlatConstants.IS_AUTH_Y);
				customer.setCs_id(cs_id);
				customerShopService.updateAuthInfo(customer);
				map.put("nickName", customer.getCs_name());// 店铺呢称
				map.put("customerNo", customer.getCs_code());// 商铺编号
				map.put("pageIndex", "3");
				LOGGER.error("---------------------结束执行速卖通授权回调成功--------------------------");
			} catch (Exception e) {
				map.put("errorMessage",
						"店铺编号【" + cs_id + "】授权失败：" + e.getMessage());
				LOGGER.error(map.get("errorMessage"));
				return new ModelAndView("merchant/error", map);
			}
			return new ModelAndView("merchant/authorize", map);
		} else {
			map.put("errorMessage", "店铺编号【" + cs_id + "】授权失败！");
			LOGGER.error(map.get("errorMessage"));
			return new ModelAndView("merchant/error", map);
		}
	}

}
